<template>
    <div class="checkbox">
        <div class="all">
            <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate"
                @change="onCheckAllChange">
                {{ props.title }}
            </a-checkbox>
        </div>
        <div class="item">
            <a-checkbox-group v-model:value="state.checkedList" :options="plainOptions"> </a-checkbox-group>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { reactive, watch, onMounted } from 'vue'
import menuStore from '@/store/menu.ts'
import { storeToRefs } from 'pinia'
const menu = menuStore()
const { routes } = storeToRefs(menu)
const props = defineProps({
    options: {
        type: Array,
        default: () => [],
    },
    title: {
        type: String,
        default: () => '',
    },
    fathers: {
        type: Array,
        default: () => [],
    },
})
const optionsValue = props.options.map((el: any) => el.value)
const plainOptions = props.options
const state: any = reactive({
    indeterminate: false,
    checkAll: false,
    checkedList: []
})

const onCheckAllChange = (e: any) => {
    const checkAll = plainOptions.map((el: any) => el.value)
    Object.assign(state, {
        checkedList: e.target.checked ? checkAll : [],
        indeterminate: false,
    })
}
watch(
    () => state.checkedList,
    val => {
        selectAllStatus()
        if (optionsValue.length == 1 && val.length > 0) {
            routes.value = [...new Set([...routes.value, ...val, ...props.fathers])]
        }
        if (optionsValue.length > 1 && val.length > 0) {
            routes.value = [...new Set([...routes.value, ...val, ...props.fathers])]
        }
    },
)
const selectAllStatus = (first: boolean = false) => {
    const val = state.checkedList
    state.indeterminate = !!val.length && val.length < plainOptions.length
    state.checkAll = val.length === plainOptions.length
    //对比变化后的值和options的值，找不到的值则从routes中删除
    let diff = optionsValue.filter((el: any) => !state.checkedList.includes(el))
    diff = [...new Set([...diff, ...props.fathers])]
    if (diff.length > 0 && first == false) {
        diff.forEach((el: any) => {
            routes.value = routes.value.filter((item: any) => item !== el)
        })

    }
}
onMounted(() => {
    optionsValue.forEach((el: any) => {
        if (routes.value.includes(el)) state.checkedList.push(el)
    })
    selectAllStatus(true)
})
</script>

<style lang="scss" scoped>
.checkbox {
    margin: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;

    .all {
        padding: 10px 0;
    }
}
</style>